<?php

namespace App\Http\Middleware;

use Closure;

class VerifySignature
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $timestamp = $request->get('_t');
        $signature = $request->get('_s');
        if (!$signature) {
            return response()->json(
                [
                    'status_code' => 400,
                    'message' => 'Missing signature',
                ],
                400
            );
        }
        $diff = abs(time() - (int)$timestamp);
        if ($diff > 300) {
            return response()->json(
                [
                    'status_code' => 408,
                    'message' => 'Request timed out',
                ],
                408
            );
        }
        $params = $request->all();
        unset($params['_s']);
        ksort($params, SORT_STRING);
        $signParams = [];
        foreach ($params as $k => $v) {
            if (!blank($v)) {
                $signParams[] = "$k=$v";
            }
        }
        $secret = config('app.key');
        $signParams[] = 'secret=' . $secret;
        $toVerifySign = strtoupper(md5(implode('&', $signParams)));
        if ($toVerifySign === $signature) {
            return $next($request);
        } else {
            return response()->json(
                [
                    'status_code' => 400,
                    'message' => 'Signature error',
                ],
                400
            );
        }
    }
}